<template>
  <a-modal 
    :visible="visible"
    :title="title"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    @cancel="closeModal()"
    width="1000px">
    <!-- <Division></Division> -->
    <div class="">
      <header>
        <div class="search">
          <a-form layout="inline">
            <a-form-item label="商品名称">
              <a-input
                style="width:180px"
                allowClear
                v-model="goodsName"
                placeholder="请输入商品名称"
              >
              </a-input>
            </a-form-item>
            <!-- <a-form-item label="商品类目">
              <a-select style="width:180px;" allowClear v-model="goodsCategory" :options="categoryList"></a-select>
            </a-form-item> -->
            <a-form-item label="商品类目">
              <a-tree-select
                  allowClear
                  style="width:180px"
                  :replaceFields="{children:'children', title:'categoryName', key:'id', value: 'id' }"
                  v-model="goodsCategory"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="categoryList"
                  placeholder="请选择"
                  tree-default-expand-all
                  >
                  <span slot="title" slot-scope="{ key, value }">
                      {{ value }}
                  </span>
              </a-tree-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleSearch">筛选</a-button>
            </a-form-item>
          </a-form>
        </div>
      </header>
      <div class="flex">
        <div class="left">
          <!-- <a-tree
              checkable
              :tree-data="treeData"
              :default-expanded-keys="['0-0-0', '0-0-1']"
              :default-selected-keys="['0-0-0', '0-0-1']"
              :default-checked-keys="['0-0-0', '0-0-1']"
              :replace-fields="replaceFields"
              @select="onSelect"
              @check="onCheck"
            /> -->
            <a-tree
              checkable
              :defaultExpandAll="true"
              :checkStrictly="true"
              :tree-data="treeData"
              :replace-fields="replaceFields"
              @check="handleTreeCheck"
            />
        </div>
        <div class="right">
          <a-button type="primary" @click="handleProductIntroduce(selectedRowKeys)">引入</a-button>
          <a-table class="table" ref="searchtable" 
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: handleSelectChange
            }"
            @selectedRowChange="handleSelectedRowChange"
            :columns="columns" :data-source="tableData" :rowKey="record=>record.id">
            <template slot="operation" slot-scope="text, record, index">
              <a rhef="javascript:;" @click="handleProductIntroduce([record.id])">引入</a>
            </template>
          </a-table>
        </div>
      </div>
    </div>
    <template slot="footer">
      <a-button @click="closeModal()">关闭</a-button>
    </template>
  </a-modal>
</template>
<script>
export default {
  components:{
   
  },
  props: {
    visible:{
      type:Boolean,
      default:false,
    },
    isApi:{
      type:Boolean,
      default:true,
    }
  },
  computed: {
    title () {
      return '商品引入'
    },
  },
  data () {
    return {
      goodsName:'',
      goodsCategory:'',
      categoryList:[],
      replaceFields: {
        children: 'children',
        title: 'orgName',
        key:'id',
      },
      treeData:[
        // {
        //   name: 'parent 1',
        //   key: '0-0',
        //   child: [
        //     {
        //       name: '张晨成',
        //       key: '0-0-0',
        //       disabled: true,
        //       child: [
        //         { name: 'leaf', key: '0-0-0-0', disableCheckbox: true },
        //         { name: 'leaf', key: '0-0-0-1' },
        //       ],
        //     },
        //     {
        //       name: 'parent 1-1',
        //       key: '0-0-1',
        //       child: [{ key: '0-0-1-0', name: 'zcvc' }],
        //     },
        //   ],
        // },
      ],
      treePlainData:[],//树形扁平化数据
      columns:[
        {
          title:'商品名称',
          dataIndex:'goodsName',
          key:'goodsName',
          customRender: (text, row) => {
            console.log('text', text)
            return <div class="product_td"><table-img src={row.goodsPicture}/><div class="product_name">{text}</div></div>
          }
        },{
          title:'商品分类',
          dataIndex:'goodsClassificationName',
          key:'goodsClassificationName'
        },
        // {
        //   title:'品牌',
        //   dataIndex:'a',
        //   key:'a'
        // },
        {
          title:'库存数量',
          dataIndex:'goodsInventory',
          key:'goodsInventory'
        },
        // {
        //   title:'商品类目',
        //   dataIndex:'c',
        //   key:'c'
        // },
        {
          title:'创建时间',
          dataIndex:'createDate',
          key:'createDate'
        },{
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        },
      ],
      tableData:[],
      pagination:{
        current:1,
        size:10,
      },
      shopIds:[],//店铺id集合
      selectedRowKeys:[],
    }
  },
  watch: {
    
  },
  created(){
    this.getOrgTree();
    this.getProductCategory();
    this.getProductList();
  },
  mounted () {
  },
  methods: {
    handleSelectedRowChange(){

    },
    handleSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    //商品类目
    async getProductCategory(){
      let res=await this.$get('/goods/category/tree',{
        categoryStatus:1
      },false,true);
      if(res && res.returnCode=='1000'){
        this.categoryList=res.dataInfo || [];
      }
      else {
        this.categoryList=[];
      }
    },
    //获取机构属性结构
    async getOrgTree(){
      let res=await this.$get('/shop/org/tree');
      if(res && res.returnCode=='1000'){
        this.treeData=res.dataInfo || [];
        this.treePlainData=this.bianping(this.treeData);
      }
    },
    //获取商品列表
    async getProductList(){
      let res=await this.$get('/goods/repository/introduce/page',{
        current:this.pagination.current,
        size:this.pagination.size,
        goodsName:this.goodsName,
        goodsCategoryId:this.goodsCategory,
        shopIds:this.shopIds.join(',')
      },false,true);
      if(res && res.returnCode=='1000'){
        this.tableData=((res.dataInfo || {}).records) || [];
        console.log('res.dataInfores.dataInfores.dataInfo',((res.dataInfo || {}).records) || []);
      }
      else {
        this.tableData=[];
      }
    },
    bianping(arr) {
      var res = [];
      for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        if (item.children.length > 0) {
          res = res.concat(this.bianping(item.children));
        }
        res.push(item);
      }
      return res;
    },
    rebuildData(value, arr) {
      if (!arr) {
        return [];
      }
      let newarr = [];
      arr.forEach((element) => {
        if (element.id.indexOf(value) > -1) {
          const ab = element.children;
          const obj = {
            ...element,
            children: ab,
          };
          newarr.push(obj);
        } else {
          if (element.children && element.children.length > 0) {
            const ab = this.rebuildData(value, element.children);
            const obj = {
              ...element,
              children: ab,
            };
            if (ab && ab.length > 0) {
              newarr.push(obj);
            }
          }
        }
      });
      return newarr;
    },
    //搜索
    handleSearch(){
      this.getProductList();
    },
    //获取选择的机构id
    getShopListByOrgIds(ids){      
      let tmpData=[];
      ids.forEach(item=>{
        let orgList=this.rebuildData(item,this.treePlainData);
        orgList.forEach(item2=>{
          tmpData.push(...item2.shopList);
        })
      });
      return tmpData.filter(item=>item);
    },
    //获取选择的机构id
    getShopListByOrgIds(ids){
      let shopIds=[];
      this.treePlainData.forEach(item=>{
        ids.forEach(item2=>{
          if(item.id==item2){
            shopIds.push(...item.shopList);
          }
        });
      })
      return shopIds;
    },
    getShopIds(data){
      return Array.from(new Set(data.map(item=>{
        return item.id;
      }))).filter(item=>item);
    },
    //选择机构
    handleTreeCheck(data){
      // console.log(data)
      let shopList=this.getShopListByOrgIds(data.checked);
      this.shopIds=this.getShopIds(shopList);
      this.getProductList();
    },
    //商品引入
    async handleProductIntroduce(ids){
      if(this.isApi){
        console.log(ids)
        if(!ids || ids.length==0){
          return this.$message.error('未选择商品');
        }
        let res=await this.$post('/goods/repository/introduce',{
          ids
        });
        if(res && res.returnCode=='1000'){
          this.goodsName='';
          this.goodsCategoryId='';
          this.shopIds='';
          this.tableData=[];
          this.$emit('cancel');
          return this.$message.success('商品引入成功');
        }
      }
      else {
        this.$emit('change',ids);
      }
    },
    closeModal (freshTable) {
      this.$emit('cancel', freshTable)
    }
  }
}
</script>

<style lang="less" scoped>
header{
  border-radius: 4px;
  background-color: #f5f5f5;
  padding: 24px 32px;
  margin-bottom:15px;
}
  .flex{
    display:flex;
    .left{
      width:240px;
    }
    .right{
      flex:1;
      margin-left:10px;
    }
  }
  .table{
    margin-top:15px;
  }
</style>
